<template>
  <div>
    <div>
      角色权限管理
    </div>
    <!--搜索框-->
    <div class="search-box">
      <!--<el-form ref="filter" :model="filter">-->
        <!--<el-form-item label="用号名称">-->
          <!--<el-input v-model="filter.name" size="small" style="width:200px;margin-right:10px;"></el-input>-->
          <!--<el-button size="small" type="warning">查询</el-button>-->
          <!--<el-button size="small" type="primary" @click="addRole">新增</el-button>-->
        <!--</el-form-item>-->
      <!--</el-form>-->
      <el-button size="small" type="primary" @click="addRole">新增</el-button>
    </div>
    <!--用户列表-->
    <div style="overflow:hidden;border-top:1px solid #ccc">
      <el-table :data="roleList" stripe style="width:100%" v-loading="loading">
        <el-table-column prop="roleId" label="角色ID" min-width="200"></el-table-column>
        <el-table-column prop="name" label="角色" min-width="200"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="200"></el-table-column>
        <el-table-column prop="roleCreateDate" label="创建时间" min-width="200"></el-table-column>
        <el-table-column label="操作" min-width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="editUser(scope.$index, scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteRole(scope.$index, scope.row)">删除</el-button>
            <el-button size="mini" type="warning" @click="roleMenu(scope.$index, scope.row)">菜单分配</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页功能-->
      <el-pagination
        style="margin-top:20px;justify-content:flex-end;display:flex;"
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page.sync="currentPage"
        :page-size="10"
        layout="prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!--新增弹窗-->
    <el-dialog title="新增角色" :visible.sync="addDialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="addForm" ref="addForm" :rules="addRules" label-width="80px" >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addForm.description" placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="addCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改弹窗-->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules" label-width="80px" >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editForm.description" placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="editCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="editSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!--菜单分配弹窗-->
    <el-dialog title="菜单分配" :visible.sync="menuVisible" width="30%" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <div style="font-size: 16px;">
        为<span style="color:#f56c6c"> {{menuRoleObj.name}} </span>分配菜单：
      </div>
      <div style="margin-top:20px;border:1px solid #ccc">
        <el-tree
          :data="menuList"
          show-checkbox
          default-expand-all
          node-key="label"
          ref="tree"
          highlight-current
          :props="defaultProps">
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="menuListCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="menuListSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import server from '../../services/index'
  var validatePhone = (rule, value, callback) => {
    if(value === ''){
      callback(new Error('请输入电话号码！'));
    }else{
      if(!(/^1(3|4|5|7|8)\d{9}$/.test(value))){
        callback(new Error('请输入正确电话号码！'));
      }
      callback();
    }
  };
  export default {
    name: "operationAccount",
    components: {},
    data () {
      return {
        filter:{
          name: "",
        },
        roleList: [],
        loading: false,
        total: 0,
        currentPage: 1,
        pageSize: 10,
        addDialogVisible: false,
        addForm: {
          name: "",
          description: ""
        },
        addRules: {
          name: [
            { required: true, message: '请输入角色名！', trigger: ['blur', 'change'] },
          ],
          description: [
            { required: true, message: '请输入角色描述！', trigger: ['blur', 'change'] },
          ]
        },
        editDialogVisible: false,
        editForm: {
          name: "",
          description: ""
        },
        editRules: {
          name: [
            { required: true, message: '请输入角色名！', trigger: ['blur', 'change'] },
          ],
          description: [
            { required: true, message: '请输入角色描述！', trigger: ['blur', 'change'] },
          ]
        },
        menuList: [],
        menuVisible: false,
        menuRoleObj: {
          roleId: "",
          name: "",
        },
        defaultProps:{
          children: 'children',
          label: 'label'
        }
      }
    },
    methods:{
      getListData(){
        this.loading = true;
        let params = {
          pageSize: this.pageSize,
          pageNum: this.currentPage,
        }
        $.ajax({
          url:server.roleList.url,
          type:'get',
          data:params,
          dataType:'json',
          success:res => {
            if(res.code == 1){
              this.loading = false;
              this.roleList = res.result.roleList;
              this.total = res.result.total;
            }
          },
          error:err =>{
            this.$message({
              message: err.responseJSON.error,
              type: 'error'
            });
          }
        });
      },
      sizeChange(val){
        this.pageSize = val;
        this.getListData();
      },
      currentChange(val){
        this.currentPage = val;
        this.getListData();
      },
      addRole(){
        this.addDialogVisible = true;
      },
      addSubmit(){
        this.$refs.addForm.validate((valid) => {
          if(valid){
            this.$confirm('确认添加新角色？').then(() => {
              let params = {
                name: this.addForm.name,
                Description: this.addForm.description
              }
              $.ajax({
                url:server.addRole.url,
                type:'post',
                data:params,
                dataType:'json',
                success:res => {
                  if(res.code == 1){
                    this.$message({
                      message: '新增成功！',
                      type: 'success'
                    });
                    this.addDialogVisible = false;
                    this.$refs.addForm.resetFields();
                    this.getListData();
                  }
                },
                error:err =>{
                  this.$message({
                    message: err.responseJSON.error,
                    type: 'error'
                  });
                }
              });
            }).catch(() => {});
          }else{
            return false;
          }
        });
      },
      addCancel(){
        this.addDialogVisible = false;
        this.$refs.addForm.resetFields();
      },
      deleteRole(index, row){
        this.$confirm('确认删除该用户？').then(() => {
          $.ajax({
            url:server.deleteRole.url,
            type:'get',
            data:{
              roleId:row.roleId
            },
            dataType:'json',
            success:res => {
              if(res.code == 1){
                this.$message({
                  message: '删除成功！',
                  type: 'success'
                });
                this.getListData();
              }
            },
            error:err =>{
              this.$message({
                message: err.responseJSON.error,
                type: 'error'
              });
            }
          });
        }).catch(() => {});
      },
      editUser(index, row){
        this.editForm.roleId = row.roleId;
        this.editForm.name = row.name;
        this.editForm.description = row.description;
        this.editDialogVisible = true;
      },
      editSubmit(){
        this.$refs.editForm.validate((valid) => {
          if(valid){
            this.$confirm('确认修改？').then(() => {
              let params = {
                roleId:this.editForm.roleId,
                name:this.editForm.name,
                description:this.editForm.description,
              }
              $.ajax({
                url:server.updateRole.url,
                type:'post',
                data:params,
                dataType:'json',
                success:res => {
                  if(res.code == 1){
                    this.$message({
                      message: '修改成功！',
                      type: 'success'
                    });
                    this.editDialogVisible = false;
                    this.$refs.editForm.resetFields();
                    this.getListData();
                  }
                },
                error:err =>{
                  this.$message({
                    message: err.responseJSON.error,
                    type: 'error'
                  });
                }
              });
            }).catch(() => {});
          }else{
            return false;
          }
        });
      },
      editCancel(){
        this.editDialogVisible = false;
        this.$refs.editForm.resetFields();
      },
      roleMenu(index, row){
        this.menuVisible = true;
        this.menuRoleObj.name = row.name;
        this.menuRoleObj.roleId = row.roleId;
        let params = {
          pageSize: this.pageSize,
          pageNum: this.currentPage,
        }
        // 请求菜单列表
        $.ajax({
          url:server.getMenuList.url,
          type:'post',
          data:params,
          dataType:'json',
          success:res => {
            var firstArr = [];
            var secondArr = [];
            res.forEach(item=>{
              if(item.menuGrade == '1'){
                firstArr.push({
                  id: item.id,
                  label: item.menuName,
                  menuId: item.menuId,
                  children: []
                })
              }
              if(item.menuGrade == '2'){
                secondArr.push({
                  id: item.id,
                  label: item.menuName,
                  menuId: item.menuId,
                  parentId: item.parentId
                })
              }
            })
            for(var i=0;i<firstArr.length;i++){
              for(var j=0;j<secondArr.length;j++){
                if(firstArr[i].menuId == secondArr[j].parentId){
                  firstArr[i].children.push(secondArr[j])
                }
              }
            }
            this.menuList = firstArr;
            this.total = res.length;
            // 菜单赋值
            $.ajax({
              url:server.roleMenu.url + '/' +row.roleId,
              type:'get',
              data:{'roleId':row.roleId},
              dataType:'json',
              success:res => {
                let arr = []
                this.$refs.tree.setCheckedKeys([]);
                if(res.result){
                  res.result.userList.forEach(item=>{
                    arr.push({
                      menuId: item.menuId,
                      label: item.menuName,
                    })
                  })
                }
                this.$refs.tree.setCheckedNodes(arr)
              },
              error:err =>{
                this.$message({
                  message: err.responseJSON.error,
                  type: 'error'
                });
              }
            });
          },
          error:err =>{
            this.$message({
              message: err.responseJSON.error,
              type: 'error'
            });
          }
        });
      },
      menuListCancel(){
        this.menuVisible = false;
        this.$refs.tree.setCheckedKeys([]);
      },
      menuListSubmit(){
        let arr = [];
        this.$refs.tree.getCheckedNodes().forEach(item=>{
          arr.push(item.menuId)
        })
        let params = {};
        params.roleId = this.menuRoleObj.roleId;
        params.menuIds = arr.join(',');
        console.log(params.menuIds)
        $.ajax({
          url:server.addRoleMenu.url,
          type:'post',
          data:params,
          dataType:'json',
          success:res => {
            console.log(res)
            this.menuListCancel();
          },
          error:err =>{
            this.$message({
              message: err.responseJSON.error,
              type: 'error'
            });
          }
        });

      },
      getNowFormatDate(time) {
        var date = time;
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        var currentdate = year + "-" + month + "-" + strDate;
        return currentdate;
      },
    },
    mounted(){
      if(!window.sessionStorage.getItem("token"))this.$router.push({path: '/'});
      this.getListData()
    }
  }
</script>

<style scoped>
  .search-box{
    margin: 20px 0;
  }
</style>
